const log4js = require('log4js');
const crypto = require('crypto');
const fs = require('fs');
const nodeUtil = require('util');

const rp = require('request-promise-native');

const config = require('./config');

// 日志
log4js.configure(config.log4js_conf);
const wxLogger = log4js.getLogger('wx');
wxLogger.setLevel(config.log_level.wx);

const errMsg = {
  '-99': '未定义的异常'
};

const logger = wxLogger;
const exists = nodeUtil.promisify(fs.exists);   //目录存在
const mkdir = nodeUtil.promisify(fs.mkdir);
const rename = nodeUtil.promisify(fs.rename);

function hexMd5 (str) {
  let md5 = crypto.createHash('md5');
  md5.update(str, 'utf-8');
  return md5.digest('hex');
}

/**
 * 创建目录，并返回路径地址，args为目录层级数组
 */
const mkdirs = (path, args)=>{
  logger.debug(`create dir: ${path}`);
  if (! fs.existsSync(path)){
    fs.mkdirSync(path);
  }
  if (args && args.length){
    let dir = args.shift();
    return mkdirs(`${path}/${dir}`, args);
  }else{
    return path;
  }
};

/**
 * 获取 access
 */
const getAccess = async ()=>{
  let options = {
    method: 'GET',
    uri: 'http://115.28.109.228:3030'
  };
  try{
    let res = await rp(options);
    return res.trim();
  }catch(e){
    console.log('获取 access token 失败：', e);
    throw e;
  }
};

module.exports = {
  logger, hexMd5, exists, mkdir, mkdirs, rename, getAccess,
  //返回的异常对象
  getErrMsg: (key) =>{
    if (errMsg[key]){
      return {
        code: key,
        msg: errMsg[key]
      }
    }else{
      return {
        code: '-99',
        msg: errMsg['-99']
      }
    }
  },
  sucResMsg: {
    code: '0',
    msg: '成功'
  },
  parseJson: (data) => {
    if (data && data.length){
      for(let row of data){
        row.content = JSON.parse(row.content);
        row.date = new Date(row.date);
      }
    }
  }
}


Date.prototype.format = function(formatStr)
{
    var str = formatStr;
    var Week = ['日', '一', '二', '三', '四', '五', '六'];

    str = str.replace(/yyyy|YYYY/, this.getFullYear());
    str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));

    var month = this.getMonth() + 1;
    str = str.replace(/MM/, month > 9 ? month.toString() : '0' + month);
    str = str.replace(/M/g, month);

    str = str.replace(/w|W/g, Week[this.getDay()]);

    str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
    str = str.replace(/d|D/g, this.getDate());

    str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
    str = str.replace(/h|H/g, this.getHours());
    str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
    str = str.replace(/m/g, this.getMinutes());

    str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
    str = str.replace(/s|S/g, this.getSeconds());

    return str;
};
